package com.yet.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.caucho.hessian.io.SerializerFactory;

public class HessianSerialization implements Serialization {

	 private SerializerFactory serializerFactory = new SerializerFactory();
	
	@Override
	public <T> byte[] serialize(T obj) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);
		ho.setSerializerFactory(serializerFactory);
		try {
			ho.writeObject(obj);
			ho.close();
		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
		return os.toByteArray();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T deserialize(byte[] bytes, Class<T> clazz) {
		ByteArrayInputStream is = new ByteArrayInputStream(bytes);
		HessianInput hi = new HessianInput(is);
		hi.setSerializerFactory(serializerFactory);
		Object readObject;
		try {
			readObject = hi.readObject();
			hi.close();
		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
		return (T) readObject;
	}
}
